import { Injector } from "../../base/utils/Injector";
import { IProtocolHelper, INetworkTips } from "./NetInterface";
import { HttpNode } from "./http/HttpNode";
import { Socket } from "./socket/Socket";
import { SocketNode } from "./socket/SocketNode";

export class NetManager {
    static PROTOCOL_HELPER_KEY: string = "app.net.protocolHelper";
    static NETWORK_TIPS_KEY: string = "app.net.networkTips";

    private _logable:boolean = false;
    private _protocol:IProtocolHelper;
    private _netTips:INetworkTips;
    private _socket:SocketNode = null;
    private _http:HttpNode = null;

    private static created:boolean = false;
    constructor(){
        if(NetManager.created){
            throw new Error("NetManager 是单例");
        }
        NetManager.created = true;
    }

    private initSocket():void {
        if(this._socket) return;
        this._protocol = Injector.getInject(NetManager.PROTOCOL_HELPER_KEY);
        this._netTips = Injector.getInject(NetManager.NETWORK_TIPS_KEY);
        
        this._socket = new SocketNode();
        let socket = new Socket();
        socket.disableInput = true;
        // socket.protocols = [];
        // socket.endian = Socket.BIG_ENDIAN;
        this._socket.init(socket, this._protocol, this._netTips);
        
        this._socket.logable = this._logable;
    }

    private initHttp(): void {
        if(this._http) return;
        this._http = new HttpNode();
    }

    public set logable(value:boolean) {
        this._logable = value;
        if(this._socket){
            this._socket.logable = value;
        }
    }

    public get socket():SocketNode{
        this.initSocket();
        return this._socket;
    }

    public get http():HttpNode{
        this.initHttp();
        return this._http;
    }

    public get server():IProtocolHelper{
        this.initSocket();
        return this._protocol;
    }
}

/**
 * 网络
 */
export var net:NetManager = new NetManager();